from django.db import models
import uuid
import re
# Create your models here.
"""
Django 数据库迁移命令: 
python manage.py makemigrations
python manage.py migrate
"""

# 用户表
class Users(models.Model):
    user_id = models.CharField(primary_key=True, verbose_name='用户ID', max_length=150)
    username = models.CharField(max_length=10, verbose_name='用户名')
    password = models.CharField(max_length=12, verbose_name='密码')
    email = models.EmailField(max_length=100, verbose_name='邮箱', unique=True)
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    def save(self, *args, **kwargs):
        # 只在创建新用户时生成 user_id
        if not self.user_id:
            self.user_id = str(uuid.uuid4())
        # 密码长度至少6位到12位
        if len(self.password) < 6 or len(self.password) > 12:
            raise ValueError({'password': "密码长度至少6位到12位"})
        # 密码只能包含字母、数字、@符号和下划线
        if not re.match(r'^[a-zA-Z0-9@_]+$', self.password):
            raise ValueError({'password': "密码只能包含字母、数字、@符号和下划线"})
        super().save(*args, **kwargs)

    class Meta:
        db_table = 'Users'

# 图片表
class Images(models.Model):
    user_id = models.ForeignKey(Users, on_delete=models.CASCADE, verbose_name='用户ID')
    image_id = models.CharField(primary_key=True, verbose_name='图片ID', max_length=150)
    image = models.FileField(upload_to='images/', verbose_name='图片')
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    # 是否识别过
    is_recognized = models.BooleanField(default=False, verbose_name='是否识别过')
    # 识别结果
    recognized_result = models.TextField(verbose_name='识别结果', null=True, blank=True)


    class Meta:
        db_table = 'Images'
    def save(self, *args, **kwargs):
        # 只在创建新图片时生成 image_id
        if not self.image_id:
            self.image_id = str(uuid.uuid4())
      
        super().save(*args, **kwargs)


# 功能id对照表
class FunctionId(models.Model):
    function_id_choices = (
        (1, '图片转文字'),
    )
    function_id = models.IntegerField(choices=function_id_choices, verbose_name='功能ID', unique=True)
    function_name = models.CharField(max_length=10, verbose_name='功能名称')
    dialogue_id = models.CharField(max_length=150, verbose_name='对话ID', null=True, blank=True)
    class Meta:
        db_table = 'FunctionId'
